﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GoogleLanguage.WebControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:LanguageManager runat=server></{0}:LanguageManager>")]
    public class LanguageManager : WebControl
    {
        public const string DEFAULT_LANGUAGE_VERSION = "1";

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Version
        {
            get
            {
                if (ViewState["Version"] == null)
                {
                    ViewState["Version"] = DEFAULT_LANGUAGE_VERSION;
                }
                return (string)ViewState["Version"];

            }
            set
            {
                ViewState["Version"] = value;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            RegisterLanguageManager();
            RegisterLiteralJavascript();
            RegisterTranslatorJavascript();
        }

        private void RegisterLanguageManager()
        {
            string scriptKey = "GoogleLanguage.WebControls.LanguageManager";

            if (!Page.ClientScript.IsClientScriptBlockRegistered(scriptKey))
            {
                StringBuilder script = new StringBuilder();
                script.Append("<script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>");
                script.Append("<script type=\"text/javascript\">");
                script.Append(String.Format("google.load(\"language\", \"{0}\");", Version));
                script.Append("</script>");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), scriptKey, script.ToString(), false);
            }
        }

        private void RegisterLiteralJavascript()
        {
            string scriptKey = "GoogleLanguage.WebControls.Literal";

            if (!Page.ClientScript.IsClientScriptIncludeRegistered(scriptKey))
            {
                Page.ClientScript.RegisterClientScriptInclude(scriptKey, ResolveUrl(Page.ClientScript.GetWebResourceUrl(this.GetType(), "GoogleLanguage.WebControls.js.Literal.js")));
            }
        }

        private void RegisterTranslatorJavascript()
        {
            string scriptKey = "GoogleLanguage.WebControls.Translator";

            if (!Page.ClientScript.IsClientScriptIncludeRegistered(scriptKey))
            {
                Page.ClientScript.RegisterClientScriptInclude(scriptKey, ResolveUrl(Page.ClientScript.GetWebResourceUrl(this.GetType(), "GoogleLanguage.WebControls.js.Translator.js")));
            }
        }
    }
}
